"""
设备资产管理工具函数
"""

import json
import uuid
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime

logger = logging.getLogger(__name__)

class AssetUtils:
    """设备资产管理工具类"""
    
    @staticmethod
    def generate_asset_id() -> str:
        """生成设备资产ID"""
        return f"AST_{uuid.uuid4().hex[:8].upper()}"
    
    @staticmethod
    def validate_asset_data(data: Dict[str, Any]) -> tuple[bool, str]:
        """
        验证设备资产数据
        
        Args:
            data: 设备资产数据
            
        Returns:
            (是否有效, 错误信息)
        """
        required_fields = ['asset_type', 'asset_name', 'asset_code']
        
        for field in required_fields:
            if not data.get(field):
                return False, f"必填字段 {field} 不能为空"
        
        # 验证资产代码格式
        asset_code = data['asset_code']
        if not isinstance(asset_code, str) or len(asset_code.strip()) == 0:
            return False, "资产代码格式不正确"
        
        # 验证数值字段
        numeric_fields = ['cpu_cores', 'memory_gb', 'storage_capacity', 'hard_disk_count']
        for field in numeric_fields:
            if field in data and data[field] is not None:
                try:
                    value = float(data[field])
                    if value < 0:
                        return False, f"{field} 不能为负数"
                except (ValueError, TypeError):
                    return False, f"{field} 必须是数字"
        
        return True, ""
    
    @staticmethod
    def validate_update_data(data: Dict[str, Any]) -> tuple[bool, str]:
        """
        验证设备资产更新数据
        
        Args:
            data: 设备资产更新数据
            
        Returns:
            (是否有效, 错误信息)
        """
        # 如果更新数据中包含资产代码，验证其格式
        if 'asset_code' in data:
            asset_code = data['asset_code']
            if not isinstance(asset_code, str) or len(asset_code.strip()) == 0:
                return False, "资产代码格式不正确"
        
        # 验证数值字段
        numeric_fields = ['cpu_cores', 'memory_gb', 'storage_capacity', 'hard_disk_count']
        for field in numeric_fields:
            if field in data and data[field] is not None:
                try:
                    value = float(data[field])
                    if value < 0:
                        return False, f"{field} 不能为负数"
                except (ValueError, TypeError):
                    return False, f"{field} 必须是数字"
        
        return True, ""
    
    @staticmethod
    def parse_device_composition(composition_str: Optional[str]) -> List[str]:
        """
        解析设备组成关系
        
        Args:
            composition_str: JSON格式的设备组成字符串
            
        Returns:
            设备ID列表
        """
        if not composition_str:
            return []
        
        try:
            composition = json.loads(composition_str)
            if isinstance(composition, list):
                return composition
            return []
        except (json.JSONDecodeError, TypeError):
            logger.warning(f"设备组成关系解析失败: {composition_str}")
            return []
    
    @staticmethod
    def format_device_composition(asset_ids: List[str]) -> str:
        """
        格式化设备组成关系
        
        Args:
            asset_ids: 设备ID列表
            
        Returns:
            JSON格式的设备组成字符串
        """
        if not asset_ids:
            return ""
        
        try:
            return json.dumps(asset_ids, ensure_ascii=False)
        except (TypeError, ValueError) as e:
            logger.error(f"设备组成关系格式化失败: {e}")
            return ""
    
    @staticmethod
    def get_asset_type_display(asset_type: str) -> str:
        """
        获取资产类型显示名称
        
        Args:
            asset_type: 资产类型代码
            
        Returns:
            显示名称
        """
        type_mapping = {
            'server': '服务器',
            'security_device': '安全设备',
            'vm_platform': '虚拟机管理平台',
            'distributed_storage': '分布式存储',
            'pc': 'PC机',
            'network_device': '网络设备'
        }
        return type_mapping.get(asset_type, asset_type)
    
    @staticmethod
    def calculate_asset_statistics(assets: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        计算设备资产统计信息
        
        Args:
            assets: 设备资产列表
            
        Returns:
            统计信息字典
        """
        stats = {
            'total_count': len(assets),
            'by_type': {},
            'total_cpu_cores': 0,
            'total_memory_gb': 0,
            'total_storage_capacity': 0,
            'by_department': {}
        }
        
        for asset in assets:
            # 按类型统计
            asset_type = asset.get('asset_type', 'unknown')
            type_name = AssetUtils.get_asset_type_display(asset_type)
            stats['by_type'][type_name] = stats['by_type'].get(type_name, 0) + 1
            
            # 按部门统计
            department = asset.get('department', '未分配')
            stats['by_department'][department] = stats['by_department'].get(department, 0) + 1
            
            # 累计硬件资源
            if asset.get('cpu_cores'):
                stats['total_cpu_cores'] += int(asset['cpu_cores'])
            if asset.get('memory_gb'):
                stats['total_memory_gb'] += float(asset['memory_gb'])
            if asset.get('storage_capacity'):
                stats['total_storage_capacity'] += float(asset['storage_capacity'])
        
        return stats
    
    @staticmethod
    def filter_assets(assets: List[Dict[str, Any]], filters: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        筛选设备资产
        
        Args:
            assets: 设备资产列表
            filters: 筛选条件
            
        Returns:
            筛选后的设备列表
        """
        filtered_assets = assets
        
        # 按资产类型筛选
        if 'asset_type' in filters and filters['asset_type']:
            filtered_assets = [
                asset for asset in filtered_assets 
                if asset.get('asset_type') == filters['asset_type']
            ]
        
        # 按部门筛选
        if 'department' in filters and filters['department']:
            filtered_assets = [
                asset for asset in filtered_assets 
                if asset.get('department') == filters['department']
            ]
        
        # 按用途筛选
        if 'purpose_desc' in filters and filters['purpose_desc']:
            purpose = filters['purpose_desc'].lower()
            filtered_assets = [
                asset for asset in filtered_assets 
                if asset.get('purpose_desc', '').lower().find(purpose) != -1
            ]
        
        # 按资产名称筛选
        if 'asset_name' in filters and filters['asset_name']:
            name = filters['asset_name'].lower()
            filtered_assets = [
                asset for asset in filtered_assets 
                if asset.get('asset_name', '').lower().find(name) != -1
            ]
        
        return filtered_assets
    
    @staticmethod
    def export_assets_to_dict(assets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        导出设备资产数据为字典格式
        
        Args:
            assets: 设备资产列表
            
        Returns:
            导出数据列表
        """
        export_data = []
        
        for asset in assets:
            export_item = {
                '资产ID': asset.get('asset_id', ''),
                '资产类型': AssetUtils.get_asset_type_display(asset.get('asset_type', '')),
                '资产名称': asset.get('asset_name', ''),
                '资产编码': asset.get('asset_code', ''),
                '型号': asset.get('model', ''),
                'CPU核数': asset.get('cpu_cores', ''),
                '内存(GB)': asset.get('memory_gb', ''),
                '存储容量(GB)': asset.get('storage_capacity', ''),
                '硬盘数量': asset.get('hard_disk_count', ''),
                '硬盘规格': asset.get('hard_disk_specs', ''),
                '部门': asset.get('department', ''),
                '用途描述': asset.get('purpose_desc', ''),
                '创建时间': asset.get('create_time', ''),
                '更新时间': asset.get('update_time', '')
            }
            export_data.append(export_item)
        
        return export_data